<?php
session_start();
date_default_timezone_set('Asia/Shanghai');

$page = $_GET['page'] ?? 'home';
$db = new PDO("sqlite:records.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 创建表（如果不存在）
$db->exec("CREATE TABLE IF NOT EXISTS records (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    record_date TEXT, 
    style_code TEXT, 
    model_type TEXT, 
    price REAL, 
    quantity INTEGER, 
    size TEXT, 
    note TEXT, 
    rope_version TEXT, 
    status TEXT DEFAULT '生产中', 
    created_at TEXT DEFAULT CURRENT_TIMESTAMP
)");
$db->exec("CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    username TEXT UNIQUE, 
    password TEXT
)");

// 迁移：为旧表添加status字段
try {
    $db->exec("ALTER TABLE records ADD COLUMN status TEXT DEFAULT '生产中'");
} catch (PDOException $e) {
    // 字段已存在，无需操作
}

// 添加索引
$db->exec("CREATE INDEX IF NOT EXISTS idx_record_date ON records (record_date)");
$db->exec("CREATE INDEX IF NOT EXISTS idx_style_code ON records (style_code)");
$db->exec("CREATE INDEX IF NOT EXISTS idx_status ON records (status)");

// 渲染公共头部
function render_header($title = '智能生产看板') {
    echo '<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>' . htmlspecialchars($title) . '</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#007bff">
</head>
<body class="bg-gray-100 font-sans">
<button class="toggle-dark fixed top-4 right-4 p-2 bg-gray-200 dark:bg-gray-700 rounded-full" onclick="toggleDarkMode()">☾</button>
<a href="#" class="back-to-top fixed bottom-16 right-4 p-2 bg-blue-500 text-white rounded-full" onclick="scrollToTop()">↑</a>
<script>
    function toggleDarkMode() { document.body.classList.toggle("dark-mode"); localStorage.setItem("darkMode", document.body.classList.contains("dark-mode") ? "1" : "0"); }
    if(localStorage.getItem("darkMode") === "1") { document.body.classList.add("dark-mode"); }
    function scrollToTop() { window.scrollTo({ top: 0, behavior: "smooth" }); }
</script>
';
}

// 渲染公共页脚（包含底部导航）
function render_footer() {
    echo '<nav class="bottom-nav fixed bottom-0 left-0 right-0 bg-white dark:bg-gray-800 shadow-lg flex justify-around py-2">
        <a href="?page=home" class="nav-item flex flex-col items-center text-blue-500">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2L2 9v12h6v-6h6v6h6V9l-10-7z"/></svg>
            <span class="text-xs">首页</span>
        </a>
        <a href="?page=add" class="nav-item flex flex-col items-center text-gray-600 dark:text-gray-300">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2a10 10 0 100 20 10 10 0 000-20zm0 9h3v2h-3v3h-2v-3H7v-2h3V7h2v4z"/></svg>
            <span class="text-xs">录入</span>
        </a>
        <a href="?page=view" class="nav-item flex flex-col items-center text-gray-600 dark:text-gray-300">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M12 4a8 8 0 100 16 8 8 0 000-16zm0 2a6 6 0 110 12 6 6 0 010-12zm-1 2h2v4h-2V8zm0 5h2v2h-2v-2z"/></svg>
            <span class="text-xs">查看</span>
        </a>';
    if (isset($_SESSION['logged_in']) && $_SESSION['logged_in']) {
        echo '<a href="?page=boss" class="nav-item flex flex-col items-center text-gray-600 dark:text-gray-300">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2a10 10 0 00-8 4h4v4H4v4h4v4H2v2h6v-4H6v-4h4v-4H8V6h8v4h-2v4h4v4h-2v4h6v-2h-4v-4h2v-4h-4V6h4a10 10 0 00-8-4z"/></svg>
            <span class="text-xs">老板</span>
        </a>
        <a href="?page=status" class="nav-item flex flex-col items-center text-gray-600 dark:text-gray-300">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2a10 10 0 00-10 10c0 5.52 4.48 10 10 10s10-4.48 10-10A10 10 0 0012 2zm-1 15v-2h2v2h-2zm0-4V7h2v6h-2z"/></svg>
            <span class="text-xs">状态</span>
        </a>
        <a href="?logout=1" class="nav-item flex flex-col items-center text-red-500">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M10 3H3v18h7v2H1V1h9v2zm11 7h-4v4h4v2h-4v2h-2v-2H7v-2h8v-4H7V8h8V6h2v2h4v2z"/></svg>
            <span class="text-xs">退出</span>
        </a>';
    } else {
        echo '<a href="?page=login" class="nav-item flex flex-col items-center text-gray-600 dark:text-gray-300">
            <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2a10 10 0 00-7 17h2a8 8 0 1112 0h2a10 10 0 00-7-17zm0 4a4 4 0 100 8 4 4 0 000-8z"/></svg>
            <span class="text-xs">登录</span>
        </a>';
    }
    echo '</nav>
    <div class="footer py-16 text-center text-gray-500 dark:text-gray-400">智慧对帐系统V1.0</div>
    </body></html>';
}

// 计算统计数据
function get_stats($db, $start_date) {
    $stmt = $db->prepare("SELECT SUM(quantity * price) as total, COUNT(*) as count, SUM(quantity) as pieces FROM records WHERE record_date >= ?");
    $stmt->execute([$start_date]);
    return $stmt->fetch(PDO::FETCH_ASSOC) ?: ['total' => 0, 'count' => 0, 'pieces' => 0];
}

// 首页
if ($page === 'home') {
    render_header();
    $today = date('Y-m-d');
    $yesterday = date('Y-m-d', strtotime("-1 day"));
    $week_start = date('Y-m-d', strtotime("last Monday"));
    $month_start = date('Y-m-d', strtotime("first day of this month"));

    $week_data = get_stats($db, $week_start);
    $month_data = get_stats($db, $month_start);

    $today_stats = $db->prepare("SELECT SUM(quantity * price) as total FROM records WHERE record_date = ?");
    $today_stats->execute([$today]);
    $today_total = $today_stats->fetchColumn() ?: 0;
    $yesterday_stats = $db->prepare("SELECT SUM(quantity * price) as total FROM records WHERE record_date = ?");
    $yesterday_stats->execute([$yesterday]);
    $yesterday_total = $yesterday_stats->fetchColumn() ?: 0;
    $compare = $yesterday_total > 0 ? round((($today_total - $yesterday_total) / $yesterday_total) * 100, 2) : 0;

    $hot_stmt = $db->query("SELECT style_code, SUM(quantity) as total_quantity FROM records GROUP BY style_code ORDER BY total_quantity DESC LIMIT 5");
    $hot_styles = $hot_stmt->fetchAll(PDO::FETCH_ASSOC);

    $model_stmt = $db->query("SELECT model_type, SUM(quantity) AS total_quantity FROM records WHERE record_date >= DATE('now', 'start of month') GROUP BY model_type");
    $model_data = $model_stmt->fetchAll(PDO::FETCH_ASSOC);

    $status_stmt = $db->query("SELECT status, COUNT(*) as count, SUM(quantity) as total_quantity FROM records WHERE record_date >= '$week_start' GROUP BY status");
    $status_data = $status_stmt->fetchAll(PDO::FETCH_ASSOC);

    echo '<div class="container mx-auto px-4 py-6">
    <div class="card mb-6 text-center">
        <h1 class="text-3xl font-bold mb-6 text-gray-800 dark:text-gray-100">智能生产看板</h1>
        <div class="flex flex-wrap justify-center gap-4">'; // 使用flex布局，适配手机和PC
    // 功能区按钮
    echo '<a href="?page=add" class="btn-custom text-blue-500 border border-blue-500 hover:bg-blue-500 hover:text-white py-2 px-4 rounded-full transition">录入</a>
          <a href="?page=view" class="btn-custom text-blue-500 border border-blue-500 hover:bg-blue-500 hover:text-white py-2 px-4 rounded-full transition">查看</a>
          <a href="?page=status" class="btn-custom text-blue-500 border border-blue-500 hover:bg-blue-500 hover:text-white py-2 px-4 rounded-full transition">状态管理</a>';
    if (isset($_SESSION['logged_in']) && $_SESSION['logged_in']) {
        echo '<a href="?page=boss" class="btn-custom text-blue-500 border border-blue-500 hover:bg-blue-500 hover:text-white py-2 px-4 rounded-full transition">老板模式</a>
              <a href="?page=backup" class="btn-custom text-yellow-500 border border-yellow-500 hover:bg-yellow-500 hover:text-white py-2 px-4 rounded-full transition">备份</a>';
    }
    echo '</div></div>
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div class="card card-stats">
            <h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">统计概览</h2>
            <div class="space-y-4">
                <div class="stat-card bg-blue-50 dark:bg-blue-900">
                    <p class="font-medium text-blue-700 dark:text-blue-300">本周</p>
                    <p class="text-gray-600 dark:text-gray-300">记录: ' . $week_data['count'] . '</p>
                    <p class="text-gray-600 dark:text-gray-300">件数: ' . $week_data['pieces'] . '</p>
                    <p class="text-lg font-bold text-blue-600 dark:text-blue-400">￥' . number_format($week_data['total'], 2) . '</p>
                </div>
                <div class="stat-card bg-green-50 dark:bg-green-900">
                    <p class="font-medium text-green-700 dark:text-green-300">本月</p>
                    <p class="text-gray-600 dark:text-gray-300">记录: ' . $month_data['count'] . '</p>
                    <p class="text-gray-600 dark:text-gray-300">件数: ' . $week_data['pieces'] . '</p>
                    <p class="text-lg font-bold text-green-600 dark:text-green-400">￥' . number_format($month_data['total'], 2) . '</p>
                </div>
                <div class="stat-card bg-yellow-50 dark:bg-yellow-900">
                    <p class="font-medium text-yellow-700 dark:text-yellow-300">今日</p>
                    <p class="text-lg font-bold text-yellow-600 dark:text-yellow-400">￥' . number_format($today_total, 2) . '</p>
                    <p class="text-sm text-gray-500 dark:text-gray-400">与昨日比 ' . ($compare >= 0 ? '+' : '') . $compare . '%</p>
                </div>
            </div>
        </div>
        <div class="card card-trend">
            <h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">金额趋势</h2>
            <div id="statsChart" style="width: 100%; height: 300px;"></div>
        </div>
        <div class="card card-model">
            <h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">型号分布</h2>
            <div id="modelChart" style="width: 100%; height: 300px;"></div>
        </div>
        <div class="card card-hot">
            <h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">热门款号 Top5</h2>
            <ul class="space-y-2">';
    foreach ($hot_styles as $style) {
        echo '<li class="flex justify-between p-2 bg-gray-50 dark:bg-gray-700 rounded-lg"><span>' . htmlspecialchars($style['style_code']) . '</span><span class="font-medium text-gray-700 dark:text-gray-300">' . intval($style['total_quantity']) . ' 件</span></li>';
    }
    echo '</ul></div>
        <div class="card card-status md:col-span-2">
            <h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">本周生产状态</h2>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">';
    foreach ($status_data as $status) {
        $status_color = $status['status'] === '生产中' ? 'bg-purple-50 dark:bg-purple-900 text-purple-700 dark:text-purple-300' : 'bg-teal-50 dark:bg-teal-900 text-teal-700 dark:text-teal-300';
        echo '<div class="stat-card ' . $status_color . '">
            <p class="font-medium">' . htmlspecialchars($status['status']) . '</p>
            <p class="text-gray-600 dark:text-gray-300">记录数: ' . $status['count'] . '</p>
            <p class="text-lg font-bold">' . $status['total_quantity'] . ' 件</p>
        </div>';
    }
    echo '</div></div>
        <div class="card card-recent md:col-span-2">
            <h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">本周录入</h2>
            <div class="overflow-x-auto">
                <table class="min-w-full table-auto">
                    <thead>
                        <tr>
                            <th class="py-3 px-2">日期</th>
                            <th class="py-3 px-2">款号</th>
                            <th class="py-3 px-2 hidden md:table-cell">型号</th>
                            <th class="py-3 px-2">数量</th>
                            <th class="py-3 px-2 hidden md:table-cell">金额</th>
                            <th class="py-3 px-2">状态</th>
                            <th class="py-3 px-2">操作</th>
                        </tr>
                    </thead>
                    <tbody>';
    $stmt = $db->prepare("SELECT * FROM records WHERE record_date >= ? ORDER BY id DESC LIMIT 5");
    $stmt->execute([$week_start]);
    foreach ($stmt as $row) {
        $amt = $row['quantity'] * $row['price'];
        echo "<tr>
            <td class='py-3 px-2'>{$row['record_date']}</td>
            <td class='py-3 px-2'>" . htmlspecialchars($row['style_code']) . "</td>
            <td class='py-3 px-2 hidden md:table-cell'>" . htmlspecialchars($row['model_type']) . "</td>
            <td class='py-3 px-2'>{$row['quantity']}</td>
            <td class='py-3 px-2 hidden md:table-cell'>￥" . number_format($amt, 2) . "</td>
            <td class='py-3 px-2'>" . htmlspecialchars($row['status']) . "</td>
            <td class='py-3 px-2'><a href='?page=view&id={$row['id']}' class='text-blue-500 underline'>详情</a></td>
        </tr>";
    }
    echo '</tbody></table></div></div>
    </div>';
    render_footer();
    echo '<script src="https://registry.npmmirror.com/echarts/5.5.0/files/dist/echarts.min.js"></script>
    <script>
        var statsChart = echarts.init(document.getElementById("statsChart"));
        var statsOption = {
            xAxis: {
                type: "category",
                data: ["本周", "本月"],
                axisLabel: { color: document.body.classList.contains("dark-mode") ? "#f1f5f9" : "#374151" }
            },
            yAxis: {
                type: "value",
                axisLabel: { color: document.body.classList.contains("dark-mode") ? "#f1f5f9" : "#374151" },
                splitLine: { lineStyle: { color: document.body.classList.contains("dark-mode") ? "rgba(255,255,255,0.1)" : "rgba(0,0,0,0.05)" } }
            },
            series: [{
                data: [' . $week_data['total'] . ', ' . $month_data['total'] . '],
                type: "bar",
                itemStyle: { color: "#60a5fa" },
                animationDuration: 1000
            }],
            grid: { left: "10%", right: "10%", bottom: "10%" }
        };
        statsChart.setOption(statsOption);

        var modelChart = echarts.init(document.getElementById("modelChart"));
        var modelOption = {
            series: [{
                type: "pie",
                radius: "50%",
                data: [';
    foreach ($model_data as $row) {
        echo '{ value: ' . $row['total_quantity'] . ', name: "' . $row['model_type'] . '" },';
    }
    echo '],
                label: { color: document.body.classList.contains("dark-mode") ? "#f1f5f9" : "#374151" },
                itemStyle: {
                    color: function(params) {
                        var colorList = ["#3b82f6", "#60a5fa", "#34d399", "#f59e0b", "#ef4444"];
                        return colorList[params.dataIndex % colorList.length];
                    }
                },
                animationDuration: 1000
            }],
            legend: {
                orient: "horizontal",
                bottom: 0,
                textStyle: { color: document.body.classList.contains("dark-mode") ? "#f1f5f9" : "#374151" }
            }
        };
        modelChart.setOption(modelOption);

        function updateChartColors() {
            const isDark = document.body.classList.contains("dark-mode");
            statsOption.xAxis.axisLabel.color = isDark ? "#f1f5f9" : "#374151";
            statsOption.yAxis.axisLabel.color = isDark ? "#f1f5f9" : "#374151";
            statsOption.yAxis.splitLine.lineStyle.color = isDark ? "rgba(255,255,255,0.1)" : "rgba(0,0,0,0.05)";
            modelOption.series[0].label.color = isDark ? "#f1f5f9" : "#374151";
            modelOption.legend.textStyle.color = isDark ? "#f1f5f9" : "#374151";
            statsChart.setOption(statsOption);
            modelChart.setOption(modelOption);
        }
        document.querySelector(".toggle-dark").addEventListener("click", updateChartColors);
    </script>';
    exit;
}
// 老板模式
if ($page === 'boss') {
    if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
        header("Location: ?page=login");
        exit;
    }
    render_header("老板模式");

    $start_date = $_GET['start_date'] ?? '';
    $end_date = $_GET['end_date'] ?? '';
    $where = '';
    $params = [];
    if ($start_date && $end_date) {
        $where = "WHERE record_date BETWEEN ? AND ?";
        $params = [$start_date, $end_date];
    }

    echo '<div class="container mx-auto px-4 py-6">
    <div class="card mb-6">
        <h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">筛选记录</h2>
        <form method="get" class="space-y-4">
            <input type="hidden" name="page" value="boss">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div><label class="block">开始日期</label><input type="date" name="start_date" value="' . htmlspecialchars($start_date) . '" class="w-full p-3 border rounded-lg"></div>
                <div><label class="block">结束日期</label><input type="date" name="end_date" value="' . htmlspecialchars($end_date) . '" class="w-full p-3 border rounded-lg"></div>
            </div>
            <button type="submit" class="btn btn-primary w-full py-3">筛选</button>
        </form>
    </div>';

    $stmt = $db->prepare("SELECT r.*, (r.quantity * r.price) as amount FROM records r $where ORDER BY r.record_date DESC");
    $stmt->execute($params);
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $total_amount = array_sum(array_column($records, 'amount'));

    echo '<div class="card mb-6">
        <h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">记录列表 (总金额: ￥' . number_format($total_amount, 2) . ')</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead><tr><th class="py-3">ID</th><th class="py-3">日期</th><th class="py-3">款号</th><th class="py-3">型号</th><th class="py-3">单价</th><th class="py-3">数量</th><th class="py-3">尺码</th><th class="py-3">绳子版</th><th class="py-3">金额</th><th class="py-3">备注</th><th class="py-3">创建时间</th></tr></thead>
                <tbody>';
    foreach ($records as $row) {
        echo "<tr><td class='py-3'>{$row['id']}</td><td class='py-3'>{$row['record_date']}</td><td class='py-3'>" . htmlspecialchars($row['style_code']) . "</td><td class='py-3'>{$row['model_type']}</td><td class='py-3'>￥{$row['price']}</td><td class='py-3'>{$row['quantity']}</td><td class='py-3'>{$row['size']}</td><td class='py-3'>{$row['rope_version']}</td><td class='py-3'>￥" . number_format($row['amount'], 2) . "</td><td class='py-3'>" . htmlspecialchars($row['note']) . "</td><td class='py-3'>{$row['created_at']}</td></tr>";
    }
    echo '</tbody></table></div></div>';

    $style_stmt = $db->prepare("SELECT style_code, SUM(quantity) as total_quantity, SUM(quantity * r.price) as total_amount FROM records r $where GROUP BY style_code ORDER BY total_amount DESC");
    $style_stmt->execute($params);
    $style_data = $style_stmt->fetchAll(PDO::FETCH_ASSOC);

    echo '<div class="card mb-6">
        <h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">款号统计</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead><tr><th class="py-3">款号</th><th class="py-3">总数量</th><th class="py-3">总金额</th></tr></thead>
                <tbody>';
    foreach ($style_data as $row) {
        echo "<tr><td class='py-3'>" . htmlspecialchars($row['style_code']) . "</td><td class='py-3'>{$row['total_quantity']}</td><td class='py-3'>￥" . number_format($row['total_amount'], 2) . "</td></tr>";
    }
    echo '</tbody></table></div></div>';
    render_footer();
    exit;
}

// 录入数据
if ($page === 'add') {
    if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
        header("Location: ?page=login");
        exit;
    }
    render_header("录入数据");
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $stmt = $db->prepare("INSERT INTO records (record_date, style_code, model_type, price, quantity, size, note, rope_version, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$_POST['record_date'], $_POST['style_code'], $_POST['model_type'], (float)$_POST['price'], (int)$_POST['quantity'], $_POST['size'], $_POST['note'], $_POST['rope_version'], $_POST['status']]);
        echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">录入成功</h2><a href="?page=add" class="btn btn-primary py-3">继续录入</a></div>';
    } else {
        echo '<div class="container mx-auto px-4 py-6"><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">录入数据</h2><form method="post" class="space-y-4">
        <div><label class="block">日期</label><input type="date" name="record_date" value="' . date('Y-m-d') . '" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">款号</label><input type="text" name="style_code" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">型号</label>
            <select name="model_type" required class="w-full p-3 border rounded-lg">
                <option value="单件">单件</option>
                <option value="两件套">两件套</option>
                <option value="三件套">三件套</option>
                <option value="四件套">四件套</option>
            </select>
        </div>
        <div><label class="block">单价</label><input type="number" name="price" step="0.01" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">数量</label><input type="number" name="quantity" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">尺码</label><input type="text" name="size" class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">绳子版</label>
            <select name="rope_version" required class="w-full p-3 border rounded-lg">
                <option value="是">是</option>
                <option value="否">否</option>
            </select>
        </div>
        <div><label class="block">备注</label><textarea name="note" class="w-full p-3 border rounded-lg"></textarea></div>
        <div><label class="block">状态</label>
            <select name="status" required class="w-full p-3 border rounded-lg">
                <option value="生产中" selected>生产中</option>
                <option value="已完成">已完成</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary w-full py-3">提交</button></form></div>';
    }
    render_footer();
    exit;
}

// 查看记录
if ($page === 'view') {
    render_header("查看记录");

    $tab = $_GET['tab'] ?? 'all';
    $search = $_GET['search'] ?? '';
    $current_page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
    $per_page = 100;
    $offset = ($current_page - 1) * $per_page;

    $today = date('Y-m-d');
    $week_start = date('Y-m-d', strtotime("last Monday"));
    $month_start = date('Y-m-d', strtotime("first day of this month"));

    $where = '';
    $params = [];
    if ($tab === 'today') {
        $where = "WHERE record_date = ?";
        $params = [$today];
    } elseif ($tab === 'week') {
        $where = "WHERE record_date >= ?";
        $params = [$week_start];
    } elseif ($tab === 'month') {
        $where = "WHERE record_date >= ?";
        $params = [$month_start];
    }

    if ($search) {
        $where .= ($where ? " AND" : "WHERE") . " (style_code LIKE ? OR model_type LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }

    $is_logged_in = isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true;

    if ($is_logged_in && isset($_GET['delete'])) {
        $id = (int)$_GET['delete'];
        $stmt = $db->prepare("DELETE FROM records WHERE id = ?");
        $stmt->execute([$id]);
        header("Location: ?page=view&tab=" . urlencode($tab) . "&search=" . urlencode($search) . "&p=" . $current_page);
        exit;
    }

    $count_stmt = $db->prepare("SELECT COUNT(*) FROM records $where");
    $count_stmt->execute($params);
    $total_records = $count_stmt->fetchColumn();
    $total_pages = ceil($total_records / $per_page);

    echo '<div class="container mx-auto px-4 py-6"><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">查看记录</h2>';

    echo '<div class="tabs flex space-x-2 overflow-x-auto">
        <a href="?page=view&tab=all" class="tab py-2 px-4 rounded-lg ' . ($tab === 'all' ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700') . '">全部</a>
        <a href="?page=view&tab=today" class="tab py-2 px-4 rounded-lg ' . ($tab === 'today' ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700') . '">当日</a>
        <a href="?page=view&tab=week" class="tab py-2 px-4 rounded-lg ' . ($tab === 'week' ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700') . '">本周</a>
        <a href="?page=view&tab=month" class="tab py-2 px-4 rounded-lg ' . ($tab === 'month' ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700') . '">本月</a>
    </div>';

    echo '<form method="get" class="search-bar mt-4">
        <input type="hidden" name="page" value="view">
        <input type="hidden" name="tab" value="' . htmlspecialchars($tab) . '">
        <input type="text" name="search" placeholder="搜索款号或型号..." value="' . htmlspecialchars($search) . '" class="w-full p-3 border rounded-lg">
        <button type="submit" class="btn btn-primary w-full py-3 mt-2">搜索</button>
    </form>';

    $stmt = $db->prepare("SELECT r.*, (r.quantity * r.price) as amount FROM records r $where ORDER BY r.record_date DESC LIMIT $per_page OFFSET $offset");
    $stmt->execute($params);

    echo '<div class="overflow-x-auto mt-4"><table class="min-w-full">
        <thead>
            <tr>
                <th class="py-3">ID</th>
                <th class="py-3">日期</th>
                <th class="py-3">款号</th>
                <th class="py-3">型号</th>
                <th class="py-3">单价</th>
                <th class="py-3">数量</th>
                <th class="py-3">尺码</th>
                <th class="py-3">绳子版</th>
                <th class="py-3">金额</th>
                <th class="py-3">备注</th>
                <th class="py-3">状态</th>
                <th class="py-3">创建时间</th>
                <th class="py-3">操作</th>
            </tr>
        </thead>
        <tbody>';
    foreach ($stmt as $row) {
        echo "<tr>
            <td class='py-3'>{$row['id']}</td>
            <td class='py-3'>{$row['record_date']}</td>
            <td class='py-3'>" . htmlspecialchars($row['style_code']) . "</td>
            <td class='py-3'>" . htmlspecialchars($row['model_type']) . "</td>
            <td class='py-3'>￥" . number_format($row['price'], 2) . "</td>
            <td class='py-3'>{$row['quantity']}</td>
            <td class='py-3'>" . htmlspecialchars($row['size']) . "</td>
            <td class='py-3'>" . htmlspecialchars($row['rope_version']) . "</td>
            <td class='py-3'>￥" . number_format($row['amount'], 2) . "</td>
            <td class='py-3'>" . htmlspecialchars($row['note']) . "</td>
            <td class='py-3'>" . htmlspecialchars($row['status']) . "</td>
            <td class='py-3'>{$row['created_at']}</td>
            <td class='py-3'>";
        if ($is_logged_in) {
            echo "<a href='?page=edit&id=" . urlencode($row['id']) . "' class='btn btn-primary btn-small py-2 px-3'>编辑</a>
                  <a href='?page=view&delete=" . urlencode($row['id']) . "&tab=" . urlencode($tab) . "&search=" . urlencode($search) . "&p=" . $current_page . "' class='btn btn-red btn-small py-2 px-3' onclick='return confirm(\"确定删除这条记录吗？\")'>删除</a>";
        } else {
            echo '<span class="text-gray-500">未登录</span>';
        }
        echo "</td></tr>";
    }
    echo '</tbody></table></div>';

    echo '<div class="pagination flex justify-center space-x-2 mt-4">';
    if ($current_page > 1) {
        echo '<a href="?page=view&tab=' . $tab . '&search=' . urlencode($search) . '&p=' . ($current_page - 1) . '" class="py-2 px-4 bg-gray-200 dark:bg-gray-700 rounded-lg">上一页</a>';
    }
    for ($i = 1; $i <= $total_pages; $i++) {
        echo '<a href="?page=view&tab=' . $tab . '&search=' . urlencode($search) . '&p=' . $i . '" class="py-2 px-4 rounded-lg ' . ($i === $current_page ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700') . '">' . $i . '</a>';
    }
    if ($current_page < $total_pages) {
        echo '<a href="?page=view&tab=' . $tab . '&search=' . urlencode($search) . '&p=' . ($current_page + 1) . '" class="py-2 px-4 bg-gray-200 dark:bg-gray-700 rounded-lg">下一页</a>';
    }
    echo '</div></div>';
    render_footer();
    exit;
}

// 编辑记录
if ($page === 'edit') {
    $id = $_GET['id'] ?? 0;
    $stmt = $db->prepare("SELECT * FROM records WHERE id = ?");
    $stmt->execute([$id]);
    $record = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$record) {
        echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">记录不存在</h2><a href="?page=view" class="btn btn-primary py-3">返回</a></div>';
        render_footer();
        exit;
    }

    render_header("编辑记录");
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $stmt = $db->prepare("UPDATE records SET record_date = ?, style_code = ?, model_type = ?, price = ?, quantity = ?, size = ?, note = ?, rope_version = ?, status = ? WHERE id = ?");
        $stmt->execute([$_POST['record_date'], $_POST['style_code'], $_POST['model_type'], (float)$_POST['price'], (int)$_POST['quantity'], $_POST['size'], $_POST['note'], $_POST['rope_version'], $_POST['status'], $id]);
        echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">更新成功</h2><a href="?page=view" class="btn btn-primary py-3">返回</a></div>';
    } else {
        echo '<div class="container mx-auto px-4 py-6"><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">编辑记录</h2><form method="post" class="space-y-4">
        <div><label class="block">日期</label><input type="date" name="record_date" value="' . htmlspecialchars($record['record_date']) . '" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">款号</label><input type="text" name="style_code" value="' . htmlspecialchars($record['style_code']) . '" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">型号</label>
            <select name="model_type" required class="w-full p-3 border rounded-lg">
                <option value="单件"' . ($record['model_type'] === '单件' ? ' selected' : '') . '>单件</option>
                <option value="两件套"' . ($record['model_type'] === '两件套' ? ' selected' : '') . '>两件套</option>
                <option value="三件套"' . ($record['model_type'] === '三件套' ? ' selected' : '') . '>三件套</option>
                <option value="四件套"' . ($record['model_type'] === '四件套' ? ' selected' : '') . '>四件套</option>
            </select>
        </div>
        <div><label class="block">单价</label><input type="number" name="price" step="0.01" value="' . htmlspecialchars($record['price']) . '" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">数量</label><input type="number" name="quantity" value="' . htmlspecialchars($record['quantity']) . '" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">尺码</label><input type="text" name="size" value="' . htmlspecialchars($record['size']) . '" class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">绳子版</label>
            <select name="rope_version" required class="w-full p-3 border rounded-lg">
                <option value="是"' . ($record['rope_version'] === '是' ? ' selected' : '') . '>是</option>
                <option value="否"' . ($record['rope_version'] === '否' ? ' selected' : '') . '>否</option>
            </select>
        </div>
        <div><label class="block">备注</label><textarea name="note" class="w-full p-3 border rounded-lg">' . htmlspecialchars($record['note']) . '</textarea></div>
        <div><label class="block">状态</label>
            <select name="status" required class="w-full p-3 border rounded-lg">
                <option value="生产中"' . ($record['status'] === '生产中' ? ' selected' : '') . '>生产中</option>
                <option value="已完成"' . ($record['status'] === '已完成' ? ' selected' : '') . '>已完成</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary w-full py-3">更新</button></form></div>';
    }
    render_footer();
    exit;
}

// 备份
if ($page === 'backup') {
    if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
        header("Location: ?page=login");
        exit;
    }
    render_header("备份数据");
    if (isset($_GET['action']) && $_GET['action'] === 'backup') {
        $backup_file = 'backup_' . date('YmdHis') . '.db';
        copy('records.db', $backup_file);
        echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">备份成功</h2><p>备份文件: ' . $backup_file . '</p><a href="?page=backup" class="btn btn-primary py-3">返回</a></div>';
    } elseif (isset($_GET['action']) && $_GET['action'] === 'restore' && isset($_GET['file'])) {
        $backup_file = $_GET['file'];
        if (file_exists($backup_file)) {
            copy($backup_file, 'records.db');
            echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">恢复成功</h2><a href="?page=backup" class="btn btn-primary py-3">返回</a></div>';
        } else {
            echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">备份文件不存在</h2><a href="?page=backup" class="btn btn-primary py-3">返回</a></div>';
        }
    } else {
        echo '<div class="container mx-auto px-4 py-6"><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">备份数据</h2>
        <a href="?page=backup&action=backup" class="btn btn-primary w-full py-3 mb-4">创建备份</a>
        <h3 class="text-lg font-semibold mb-2">现有备份</h3>';
        $backups = glob('backup_*.db');
        if ($backups) {
            echo '<ul class="space-y-2">';
            foreach ($backups as $backup) {
                echo '<li class="flex justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"><span>' . $backup . '</span><a href="?page=backup&action=restore&file=' . $backup . '" class="btn btn-yellow btn-small py-2 px-3" onclick="return confirm(\'确定恢复这个备份吗？\')">恢复</a></li>';
            }
            echo '</ul>';
        } else {
            echo '<p>暂无备份文件</p>';
        }
        echo '</div>';
    }
    render_footer();
    exit;
}

// 生产状态管理
if ($page === 'status') {
    if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in']) {
        header("Location: ?page=login");
        exit;
    }
    render_header("生产状态管理");

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id']) && isset($_POST['status'])) {
        $stmt = $db->prepare("UPDATE records SET status = ? WHERE id = ?");
        $stmt->execute([$_POST['status'], (int)$_POST['id']]);
        echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">状态更新成功</h2><a href="?page=status" class="btn btn-primary py-3">返回</a></div>';
        render_footer();
        exit;
    }

    $search = $_GET['search'] ?? '';
    $current_page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
    $per_page = 50;
    $offset = ($current_page - 1) * $per_page;

    $where = '';
    $params = [];
    if ($search) {
        $where = "WHERE (style_code LIKE ? OR model_type LIKE ?)";
        $params = ["%$search%", "%$search%"];
    }

    $count_stmt = $db->prepare("SELECT COUNT(*) FROM records $where");
    $count_stmt->execute($params);
    $total_records = $count_stmt->fetchColumn();
    $total_pages = ceil($total_records / $per_page);

    echo '<div class="container mx-auto px-4 py-6"><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">生产状态管理</h2>';

    echo '<form method="get" class="search-bar mt-4">
        <input type="hidden" name="page" value="status">
        <input type="text" name="search" placeholder="搜索款号或型号..." value="' . htmlspecialchars($search) . '" class="w-full p-3 border rounded-lg">
        <button type="submit" class="btn btn-primary w-full py-3 mt-2">搜索</button>
    </form>';

    $stmt = $db->prepare("SELECT * FROM records $where ORDER BY record_date DESC LIMIT $per_page OFFSET $offset");
    $stmt->execute($params);

    echo '<div class="overflow-x-auto mt-4"><table class="min-w-full">
        <thead>
            <tr>
                <th class="py-3">ID</th>
                <th class="py-3">日期</th>
                <th class="py-3">款号</th>
                <th class="py-3">型号</th>
                <th class="py-3">数量</th>
                <th class="py-3">状态</th>
                <th class="py-3">操作</th>
            </tr>
        </thead>
        <tbody>';
    foreach ($stmt as $row) {
        echo "<tr>
            <td class='py-3'>{$row['id']}</td>
            <td class='py-3'>{$row['record_date']}</td>
            <td class='py-3'>" . htmlspecialchars($row['style_code']) . "</td>
            <td class='py-3'>" . htmlspecialchars($row['model_type']) . "</td>
            <td class='py-3'>{$row['quantity']}</td>
            <td class='py-3'>" . htmlspecialchars($row['status']) . "</td>
            <td class='py-3'>
                <form method='post' class='inline'>
                    <input type='hidden' name='id' value='{$row['id']}'>
                    <select name='status' class='p-2 border rounded-lg' onchange='this.form.submit()'>
                        <option value='生产中'" . ($row['status'] === '生产中' ? ' selected' : '') . ">生产中</option>
                        <option value='已完成'" . ($row['status'] === '已完成' ? ' selected' : '') . ">已完成</option>
                    </select>
                </form>
            </td>
        </tr>";
    }
    echo '</tbody></table></div>';

    echo '<div class="pagination flex justify-center space-x-2 mt-4">';
    if ($current_page > 1) {
        echo '<a href="?page=status&search=' . urlencode($search) . '&p=' . ($current_page - 1) . '" class="py-2 px-4 bg-gray-200 dark:bg-gray-700 rounded-lg">上一页</a>';
    }
    for ($i = 1; $i <= $total_pages; $i++) {
        echo '<a href="?page=status&search=' . urlencode($search) . '&p=' . $i . '" class="py-2 px-4 rounded-lg ' . ($i === $current_page ? 'bg-blue-500 text-white' : 'bg-gray-200 dark:bg-gray-700') . '">' . $i . '</a>';
    }
    if ($current_page < $total_pages) {
        echo '<a href="?page=status&search=' . urlencode($search) . '&p=' . ($current_page + 1) . '" class="py-2 px-4 bg-gray-200 dark:bg-gray-700 rounded-lg">下一页</a>';
    }
    echo '</div></div>';
    render_footer();
    exit;
}

// 登录
if ($page === 'login') {
    render_header("登录");
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $stmt = $db->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
        $stmt->execute([$_POST['username'], md5($_POST['password'])]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($user) {
            $_SESSION['logged_in'] = true;
            header("Location: ?page=home");
            exit;
        } else {
            echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">用户名或密码错误</h2><a href="?page=login" class="btn btn-primary py-3">重试</a></div>';
        }
    } else {
        echo '<div class="container mx-auto px-4 py-6"><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">登录</h2><form method="post" class="space-y-4">
        <div><label class="block">用户名</label><input type="text" name="username" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">密码</label><input type="password" name="password" required class="w-full p-3 border rounded-lg"></div>
        <button type="submit" class="btn btn-primary w-full py-3">登录</button></form>
        <p class="mt-4 text-center">没有账号？<a href="?page=register" class="text-blue-500">注册</a></p></div>';
    }
    render_footer();
    exit;
}

// 注册
if ($page === 'register') {
    render_header("注册");
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        try {
            $stmt = $db->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
            $stmt->execute([$_POST['username'], md5($_POST['password'])]);
            echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">注册成功</h2><a href="?page=login" class="btn btn-primary py-3">去登录</a></div>';
        } catch (PDOException $e) {
            echo '<div class="container mx-auto px-4 py-6"><div class="card text-center"><h2 class="text-xl font-semibold mb-4">用户名已存在</h2><a href="?page=register" class="btn btn-primary py-3">重试</a></div>';
        }
    } else {
        echo '<div class="container mx-auto px-4 py-6"><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700 dark:text-gray-200">注册</h2><form method="post" class="space-y-4">
        <div><label class="block">用户名</label><input type="text" name="username" required class="w-full p-3 border rounded-lg"></div>
        <div><label class="block">密码</label><input type="password" name="password" required class="w-full p-3 border rounded-lg"></div>
        <button type="submit" class="btn btn-primary w-full py-3">注册</button></form>
        <p class="mt-4 text-center">已有账号？<a href="?page=login" class="text-blue-500">去登录</a></p></div>';
    }
    render_footer();
    exit;
}

// 退出登录
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: ?page=home");
    exit;
}
?>